console.log('load libs ...')

var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var path = require('path');
var https = require('https');
var http = require('http');
var fileupload = require("express-fileupload");
var format = require('string-format');
format.extend(String.prototype);
var shelljs = require('shelljs');

class TWebServer{
    constructor(){
        this.config = {
            port: 2000,
            statics:{
                "/":"D:/project/webstatics",
                '/web':"D:/project/webstatics"
            }
        };
        this.handlers ={};
    }

    start(){
        var  me = this;
        return new Promise((success, faild)=>{
            try{
                var app = express();
                var staticKeys = Object.keys(me.config.statics);
                staticKeys.forEach( st=>{ 
                    var key = st;
                    var value = me.config.statics[key];
                    app.use(st, express.static(value));
                });

                
                var urlencodedParser = bodyParser.urlencoded({ extended: false });
                app.use(urlencodedParser);
                app.use(bodyParser.json());
                app.use(fileupload());
                var jsonParser = bodyParser.json();                
                app.get("/", jsonParser, (resquest , response)=>{
                    console.log('on get svr time...');
                    response.send('root/');
                }); 
                Object.keys( me.handlers).forEach( hk=>{
                    var h = me.handlers[hk];
                    app.get( hk , jsonParser, (req , resp)=>{
                        h(req , resp);
                    })
                })
                
                var websvr = http.createServer(app);
                websvr.listen( me.config.port , ()=>{
                    console.log('start web server on port :'+ me.config.port);
                    success();
                } )
            }
            catch(er){
                console.log(er);
                success();
            }
        })
    };
    registAction(action , handler){
        var me = this;
        me.handlers[action] = (req, resp)=>{
            handler(req , resp);
        }
    }
};

console.log('start server')

var websvr = new TWebServer();

websvr.registAction("/query" , (req ,resp)=>{
    resp.send('/query');
})

websvr.start().then(_=>{
    console.log('start web server success.');
})